const Router = require('express').Router
const express = require('express')
const { root } = require('../contants')
const { AuthMiddleWare } = require('../middleware/auth')
const { asyncException } = require('../util/async-execption')
const HomeController = require('../controller/home')
const RepoController = require('../controller/repo')
const Contants = require('../contants')
const router = Router()

// 忽略
const hashIgnore = {
    login: true,
    assets: true,
    manage: true,
    new: true,
    "favicon.ico": true,
    '404': true,
}

router.get('/404', (req, res) => {
    res.render('404.njk')
})

router.get('/login', (req, res) => {
    res.render('login.njk', {
        ROOT: Contants.root,
    })
})

router.get('/', AuthMiddleWare(true), (req, res) => {
    const __user__ = req.__user__
    res.redirect(root + __user__.username)
})

router.post('/login', express.urlencoded(), asyncException(async (req, res) => {
    const { username, password } = req.body
    const context = {
        username,
        password,
        token: null,
    }
    const homeController = new HomeController()
    if (username && password) {
        await homeController.login(context)
        if (context.token) {
            res.setHeader('Set-Cookie', `token=${context.token}`)
            res.redirect(`${Contants.root}${username}`)
        } else {
            res.status(400).render('login.njk')
        }
    } else {
        res.status(400).render('login.njk')
    }
}))

router.get('/new', AuthMiddleWare(true), asyncException(async (req, res) => {
    const __user__ = req.__user__
    const session = __user__ ? true : false

    const context = {
        ROOT: Contants.root,
        session,
        user: {
            username: __user__.username,
        },
    }
    res.render('create-repo.njk', context)
}))

router.post('/new', express.urlencoded(), AuthMiddleWare(true), asyncException(async (req, res) => {
    const __user__ = req.__user__
    const session = __user__ ? true : false
    const homeController = new HomeController()
    const context = {
        ROOT: Contants.root,
        session,
        user: {
            username: __user__.username,
        },
        ...req.body,
    }
    const succ = await homeController.createRepo(context)
    if (succ) {
        res.redirect(`${Contants.root}${__user__.username}/${context.name}`)
    } else {
        res.redirect(`${Contants.root}new`)
    }
}))

// 使用 /:param 时，要注意首页默认favicon.ico也会走这个路由
router.get(['/:username/:repo/:type/:branch/*', '/:username/:repo/:type/:branch', '/:username/:repo' ,'/:username'], AuthMiddleWare(false) ,asyncException(async (req, res, next) => {
    const __user__ = req.__user__
    const session = __user__ ? true : false
    
    const {username, repo, type, branch, 0: path } = req.params
    if (hashIgnore[username]) {
        return next()
    }
    if (username && repo && type && branch && path) {
        const context = {
            ROOT: Contants.root,
            user: {
                username,
                session,
            },
            repo: {
                name: repo,
                branch,
                branchArray: [],
                path,
                git_http_url: '',
                profile: {
                    description: '',
                    website: '',
                },

                fileList: [],
            },
            type,
        }
        const repoController = new RepoController()
        if (type === 'blob') {   
            await repoController.blob(context)
        } else if (type === 'tree') {
            await repoController.repo(context)
        }
        res.render('repo.njk', context)
    } else if (username && repo && type && branch) {
        const context = {
            ROOT: Contants.root,
            user: {
                username,
                session,
            },
            repo: {
                name: repo,
                path: '',
                branch,
                branchArray: [],
                git_http_url: '',
                is_empty_repo: false,
                profile: {
                    description: '',
                    website: '',
                },

                fileList: [],
            },
            type,
        }
        const repoController = new RepoController()
        await repoController.repo(context)
    
        res.render('repo.njk', context)
    } else if (username && repo) {
        const context = {
            ROOT: Contants.root,
            user: {
                username,
                session,
            },
            repo: {
                name: repo,
                path: '',
                branch: '',
                branchArray: [],
                git_http_url: '',
                is_empty_repo: false,
                profile: {
                    description: '',
                    website: '',
                },

                fileList: [],
            },
            type: 'tree',
        }
        const repoController = new RepoController()
        await repoController.repo(context)
        // 如果是master分支，或者是空仓库（没有分支）都直接render
        if (context.repo.branch === 'master' || context.repo.is_empty_repo) {
            res.render('repo.njk', context)
        } else {
            res.redirect(`${Contants.root}${username}/${repo}/tree/${context.repo.branch}`)
        }
    } else if (username && !repo) {
        const { tab } = req.query;
        const context = {
            ROOT: Contants.root,
            user: {
                username,
                session,
            }
        }
        const homeController = new HomeController
        if (tab === 'repositories') {
            await homeController.repositories(context)
        } else {
            await homeController.overviews(context)
        }
        res.render('profile.njk', context)
    }
}))

module.exports = router